import Taro, { Component } from '@tarojs/taro'
import { Button } from '@tarojs/components'

import authority from '@/utils/authority'
// import { login, wxPhoneLogin } from '@/utils/login'
import { redirectBack, query as getCurrentOptions } from '@/utils/router'
import { login, wxPhoneLogin } from '@/utils/login'

import setting from '@/utils/setting'

import './index.scss'

export default class index extends Component {
  state = {
    hasSetting: false
  }

  componentDidShow() {
    authority.clear()
    login()
  }

  componentDidMount() {
    this.validateSetting()
  }

  validateSetting = async () => {
    const data = await setting.get()
    this.hasSetting = await setting.has('userInfo')
  }

  toBind = () => {
    const { back = '' } = getCurrentOptions()
    Taro.navigateTo({
      url: `/pages/bind/index?back=${back}`
    })
  }

  async wxPhoneLogin(e) {
    const { encryptedData, iv } = e.target
    if (!encryptedData) {
      return this.toBind()
    }
    wxPhoneLogin({
      encrypted_data: encryptedData,
      iv
    })
      .then(() => {
        Taro.showToast({
          title: '登陆成功'
        })
        redirectBack()
      })
      .catch(e => {
        console.error(e)
        this.toBind()
      })
  }

  async login(e) {
    await this.wxPhoneLogin(e)
  }

  render() {
    const { hasSetting } = this.state
    return hasSetting ? (
      <Button
        className='center-flex btn wx-btn'
        hover-className='opacity'
        onClick={this.login}
      >
        <Image src={require('./images/wechat.png')} className='wx-icon' />
        <View className='wx-text'>微信手机号登陆</View>
      </Button>
    ) : (
      <Button
        className='center-flex btn wx-btn'
        hover-className='opacity'
        open-type='getPhoneNumber'
        onGetphonenumber={this.wxPhoneLogin}
      >
        <Image src={require('./images/wechat.png')} className='wx-icon' />
        <View className='wx-text'>微信手机号登陆</View>
      </Button>
    )
  }
}
